package com.nbstar.film.spider.excel;

import com.nbstar.film.spider.domain.FilmSpiderDomain;
import com.nbstar.film.spider.pojo.*;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

public abstract class XSSExcelWriter  implements IExcelWriter{
    private static Logger logger = LoggerFactory.getLogger(SiChuanExcelWriter.class);

    private Sheet sheet;
    private String sheetName;
    private XSSFWorkbook wb;
    private  String excelPath;

    public XSSExcelWriter(String sheetName, String excelPath) {
        this.sheetName = sheetName;
        this.excelPath = excelPath;
    }

    protected abstract void initExcelHeader(Row header);

    protected abstract void writeRow(Row row, FilmExcelInfo filmDomain);

    @Override
    public void initEXcelFile() throws IOException {
        wb = new XSSFWorkbook();
        sheet = wb.createSheet(sheetName); //重命名sheet1的工作表名
        Row r = sheet.createRow(0);
        initExcelHeader(r);
        FileOutputStream fos = new FileOutputStream(excelPath);
        fos.flush();
        wb.write(fos);

        fos.close();
        wb.close();
    }



    @Override
    public synchronized void writeVedio2Excel(FilmSpiderDomain domain) {
        BufferedOutputStream outPutStream  = null;
        FilmExcelInfo filmDomain = (FilmExcelInfo) trans2Excel(domain);

        //out = new FileOutputStream(excelPath);
        try {
            wb = new XSSFWorkbook(new FileInputStream(excelPath));
            sheet = wb.getSheet(sheetName);

            int rowNum = sheet.getLastRowNum();
            Row r = sheet.createRow(rowNum + 1);
            writeRow(r, filmDomain);
            outPutStream = new BufferedOutputStream(new FileOutputStream(excelPath));
            wb.write(outPutStream); //导出excel
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outPutStream.close();
                wb.close();
//                outPutStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
